package com.wang.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.JustForTest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.common.utils.HttpUtils;
import com.wang.common.utils.PageUtils;
import com.wang.common.utils.Query;
import com.wang.common.vo.MemberResponseVo;
import com.wang.gulimall.member.dao.MemberDao;
import com.wang.gulimall.member.dao.MemberLevelDao;
import com.wang.gulimall.member.entity.MemberEntity;
import com.wang.gulimall.member.entity.MemberLevelEntity;
import com.wang.gulimall.member.exception.PhoneException;
import com.wang.gulimall.member.exception.UsernameException;
import com.wang.gulimall.member.service.MemberService;
import com.wang.gulimall.member.vo.MemberUserLoginVo;
import com.wang.gulimall.member.vo.MemberUserRegisterVo;
import com.wang.gulimall.member.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringExclude;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @JustForTest
    public void test(){

    }

    //注册会员服务 也就是往ums_member表中插入用户名，密码，电话等信息以及默认信息
    @Override
    public void register(MemberUserRegisterVo vo) {
        log.info("开始处理会员注册");
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();

        //设置默认等级信息
        MemberLevelEntity defaultLevel = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(defaultLevel.getId());

        //检查用户名和手机号码是否唯一
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        //用户手机号
        memberEntity.setMobile(vo.getPhone());
        //用户名字
        memberEntity.setUsername(vo.getUserName());

        //密码进行MD5加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setGender(0);
        memberEntity.setCreateTime(new Date());

        //保存数据
        memberDao.insert(memberEntity);
    }

    //检查手机号是否唯一
    @Override
    public void checkPhoneUnique(String phone) throws PhoneException {
        Integer phoneCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        //之前该记录已经存在，则会抛出异常
        if (phoneCount > 0) {
            throw new PhoneException();
        }

    }

    //检查用户名是否唯一
    @Override
    public void checkUserNameUnique(String userName) throws UsernameException {
        Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        //之前该记录已经存在，则会抛出异常
        if (usernameCount > 0) {
            throw new UsernameException();
        }
    }

    //普通登录
    @Override
    public MemberEntity login(MemberUserLoginVo vo) {
        //用户名
        String loginacct = vo.getLoginacct();
        //密码
        String password = vo.getPassword();

        //1、去数据库查询 SELECT * FROM ums_member WHERE username = ? OR mobile = ?
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", loginacct).or().eq("mobile", loginacct));
        if (memberEntity == null) {
            //登录失败
            return null;
        } else {
            //获取到数据库里的password
            String password1 = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //进行密码匹配
            boolean matches = passwordEncoder.matches(password, password1);
            if (matches) {
                //登录成功
                return memberEntity;
            }
        }
        return null;
    }

    //社交用户登录 注册+登录两个逻辑
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {

        //具有登录和注册逻辑
        String uid = socialUser.getUid();

        //1、判断当前社交用户是否已经登录过系统
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        //这个用户已经注册过
        if (memberEntity != null) {
            //更新用户的访问令牌的时间和access_token
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            //update.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.updateById(update);

            memberEntity.setAccessToken(socialUser.getAccess_token());
           //memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            //2、没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity register = new MemberEntity();
            //3、查询当前社交用户的社交账号信息（昵称、性别等）从微博服务器获取用户信息     只有获取到accesskey才可以到微博服务器下的得到数据
            Map<String, String> query = new HashMap<>();
            query.put("access_token", socialUser.getAccess_token());
            query.put("uid", socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);

            if (response.getStatusLine().getStatusCode() == 200) {
                //查询成功
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String name = jsonObject.getString("name");
                String gender = jsonObject.getString("gender");
                String profileImageUrl = jsonObject.getString("profile_image_url");

                register.setNickname(name);
                register.setGender("m".equals(gender) ? 1 : 0);
                register.setHeader(profileImageUrl);
                register.setCreateTime(new Date());
                register.setSocialUid(socialUser.getUid());
                register.setAccessToken(socialUser.getAccess_token());
                //register.setExpiresIn(socialUser.getExpires_in());

                //把用户信息插入到数据库中
                this.baseMapper.insert(register);
            }
            return register;
        }

    }

    @Override
    public MemberEntity login(String accessTokenInfo) {
        return null;
    }


    /**
     * 微博第三方用户登录
     * @return
     * @param vo
     */
    @Override
    public MemberResponseVo authRegister(MemberResponseVo vo) {
        // vo中含有uid，username,nickname
        MemberEntity registerMember = new MemberEntity();
        // 设置注册用户的基本信息
        registerMember.setUsername(vo.getUsername());
        registerMember.setNickname(vo.getNickname());
        registerMember.setLevelId(vo.getLevelId());
        registerMember.setCreateTime(new Date());

        this.save(registerMember);
        // 返回的用户登录信息
        MemberResponseVo returnUser = new MemberResponseVo();

        returnUser.setId(registerMember.getId());
        BeanUtils.copyProperties(registerMember,returnUser);

        System.out.println(returnUser);

        return returnUser;
    }
}